{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 用money/刷卡次数/平均单次消费为聚类字段\n",
    "# data1['day']=pd.DatetimeIndex(data1['Date']).day\n",
    "q1=[]\n",
    "q2=[]\n",
    "q3=[]\n",
    "for i in data1['CardNo'].value_counts().index:\n",
    "    major=data1[data1['CardNo']==i]\n",
    "    q1.append(i)#卡号\n",
    "    q2.append(sum(major['Money']))#卡号对应的money\n",
    "    q3.append(len(major['Money'])-sum(major.duplicated(['day','hour'])))#刷卡频次统计：刷卡时间相近的算一次消费\n",
    "# print(q1)\n",
    "# print(q2)\n",
    "s1=pd.Series(q1,index=range(1,len(q1)+1),name='学号')\n",
    "s2=pd.Series(q2,index=range(1,len(q2)+1),name='金额')\n",
    "s3=pd.Series(q3,index=range(1,len(q3)+1),name='刷卡次数')\n",
    "df=pd.DataFrame({s1.name:s1,s2.name:s2,s3.name:s3})\n",
    "df.describe()\n",
    "#对要聚类的字段进行数据处理：消除一些刷卡次数少的人以及一些异常值\n",
    "a = df[\"刷卡次数\"].quantile(0.75)\n",
    "b = df[\"刷卡次数\"].quantile(0.25)\n",
    "c = df[\"金额\"].quantile(0.75)\n",
    "d = df[\"金额\"].quantile(0.25)\n",
    "demoney =df[\"刷卡次数\"]\n",
    "jine=df[\"金额\"]\n",
    "de=df[(jine>=(c-d)*1.5+c)|(demoney<=b)].index\n",
    "df=df.drop(de)\n",
    "df[\"平均单次消费\"]=df[\"金额\"]/df[\"刷卡次数\"]\n",
    "def ZscoreNormalization(x):#标准化\n",
    "    \"\"\"Z-score normaliaztion\"\"\"\n",
    "    x = (x - np.min(x)) / (np.max(x)-np.min(x))\n",
    "    return x\n",
    "df['金额']=ZscoreNormalization(df['金额'])\n",
    "df['刷卡次数']=ZscoreNormalization(df['刷卡次数'])\n",
    "df['平均单次消费']=ZscoreNormalization(df['平均单次消费'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.cluster import KMeans\n",
    "from sklearn.cluster import Birch\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "d=df[['金额','刷卡次数','平均单次消费']]\n",
    "mod = KMeans(n_clusters=4, max_iter = 1000)#聚成3类数据,并发数为4，最大循环次数为500\n",
    "mod.fit_predict(d)#y_pred表示聚类的结果\n",
    "\n",
    "r1 = pd.Series(mod.labels_).value_counts()\n",
    "r2 = pd.DataFrame(mod.cluster_centers_)\n",
    "r = pd.concat([r2, r1], axis = 1)\n",
    "r.columns = list(d.columns) + [u'类别数目']\n",
    "print(r)\n",
    "#给每一条数据标注上被分为哪一类\n",
    "r = pd.concat([d, pd.Series(mod.labels_, index = d.index)], axis = 1)\n",
    "r.columns = list(d.columns) + [u'聚类类别']\n",
    "print(r)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
